package io.github.jieblog.juc.day2;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * Created by jie on 2017/3/13.
 */
public class AtomicIntegerFieldUpdaterDemo {
    static class Student {
        int id;
        volatile int score;
    }

    private final static AtomicIntegerFieldUpdater<Student> studentAtomicIntegerFieldUpdater = AtomicIntegerFieldUpdater.newUpdater(Student.class, "score");

    static class Task implements Runnable {
        private Student stu;

        public Task(Student stu) {
            this.stu = stu;
        }

        @Override
        public void run() {
            if (Math.random() > 0.5) {
                studentAtomicIntegerFieldUpdater.incrementAndGet(stu);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Student stu = new Student();
        Thread[] t = new Thread[10000];

        for (int i = 0; i < 10000; i++) {
            t[i] = new Thread(new Task(stu));
            t[i].start();
        }

        for (int i = 0; i < 10000; i++) {
            t[i].join();
        }

        System.out.println("score=" + stu.score);
    }
}

